import React, { Component } from 'react';
import { PlusOutlined } from '@ant-design/icons';
import { Card, message, Button } from 'antd';
import { connect } from 'dva';
import PropTypes from 'prop-types';
import Ellipsis from '../../../components/Ellipsis';
import PateoTable from '../../../components/common/PateoTable';
import PateoSearchForm from '../../../components/common/PateoSearchForm';
import PateoAuthButtons from '../../../components/common/PateoAuthButtons';
import PateoModalForm from '../../../components/common/PateoModalForm';
import { filterAuth } from '@/support/common';

const mapStateToProps = (state: any) => ({
  template: state.template,
  user: state.user,
  loading: state.loading.models['template'],
});
class ImportTemplateList extends Component<any, any> {
  static contextTypes = {
    dicData: PropTypes.object,
    permissions: PropTypes.array,
  };

  state = {
    formValues: {},
    visible: false,
    postUrl: '',
    formData: {},
    brandList: [],
  };

  componentDidMount() {
    this.handleRefresh();
  }

  handleRefresh = () => {
    const { dispatch } = this.props;
    dispatch({
      type: 'template/postFetchPage',
      payload: { url: '/template/page' },
    });
  };

  handleNotice = () => {
    message.success('操作成功！');
    this.handleRefresh();
  };

  handleDelete = (sid: any) => {
    const { dispatch } = this.props;
    dispatch({
      type: 'template/delData',
      payload: { url: `/template/del?templateCode=${sid}` },
      callback: (response: any) => this.handleNotice(),
    });
  };

  handleAdd = () => {
    this.setState({
      visible: true,
      postUrl: '/template/add',
    });
  };

  handleEdit = (record: any) => {
    this.setState({
      formData: record,
      visible: true,
      postUrl: '/template/edit',
    });
  };

  handleFlushPage = (flag = undefined) => {
    const { dispatch } = this.props;
    const { formValues } = this.state;
    dispatch({
      type: 'template/postFetchPage',
      payload: { url: '/template/page', ...formValues },
    });
  };

  render() {
    const { location: { pathname = '/' } } = this.props;
    const {
      template: {
        pageData: { list, pagination },
      },
      loading
    } = this.props;
    const { formValues, visible, postUrl, formData } = this.state;
    const columns = [
      {
        title: '模版名称',
        dataIndex: 'templateName',
        render: (text: any) => (
          <Ellipsis length={16} tooltip>
            {text}
          </Ellipsis>
        ),
      },
      {
        title: '模版编码',
        dataIndex: 'templateCode',
        render: (text: any) => (
          <Ellipsis length={16} tooltip>
            {text}
          </Ellipsis>
        ),
      },
      {
        title: '模版地址',
        dataIndex: 'templateUrl',
        render: (text: any) => <a target="_blank" href={text} title="点击下载模板文件">模板文件下载</a>
      },
      {
        title: '模版说明',
        dataIndex: 'templateDesc',
        render: (text: any) => (
          <Ellipsis length={16} tooltip>
            {text}
          </Ellipsis>
        )
      },
      {
        title: '操作',
        dataIndex: '操作',
        width: 150,
        render: (text: any, record: any) => {
          const btns = [
            {
              title: '编辑',
              key: 'edit',
              auth: "template_doEdit",
              onConfirm: () => this.handleEdit(record),
            },
            {
              title: '删除',
              key: 'del',
              auth: "template_doDel",
              message: '是否确认删除？',
              Popconfirm: true,
              onConfirm: () => this.handleDelete(record.templateCode),
            }
          ];
          return <PateoAuthButtons pathname={pathname} btns={btns} max={1} />;
        },
      },
    ];
    const searchItems = [
      {
        type: 'input',
        title: '模版名称',
        key: 'templateName',
      },
      {
        type: 'input',
        title: '模版编码',
        key: 'templateCode',
      },
      {
        type: 'input',
        title: '模版说明',
        key: 'templateDesc',
      },
    ];
    const paginationProps = {
      showSizeChanger: true,
      showQuickJumper: true,
      ...pagination,
      showTotal: () => (
        <span>共&nbsp;{pagination === undefined ? 0 : pagination.total}&nbsp;条</span>
      ),
    };
    const tableProps = {
      columns,
      dataSource: list,
      loading,
      rowKey: (record: any) => record.sid,
      pagination: paginationProps,
    };
    const formItems = [
      {
        type: 'input',
        title: '模版名称',
        key: 'templateName',
        rules: [{ required: true, message: '请输入模版名称！', whitespace: true, max: 50 }],
        maxLength: 50,
      },
      {
        type: 'input',
        title: '模版编码',
        key: 'templateCode',
        rules: [{ required: true, message: '请输入模版编码！', whitespace: true, max: 50 }],
        maxLength: 50,
      },
      {
        type: 'file',
        title: '模版地址',
        key: 'templateUrl',
        rules: [{ required: true, message: '请上传！' }],
        suffix: "xls,xlsx,doc,docx"
      },
      {
        type: 'textArea',
        title: '模版说明',
        key: 'templateDesc',
        rules: [{ required: false, message: '请输入描述！', max: 200 }],
        maxLength: 200,
      },
    ];
    return (
      <div>
        <Card title="" bordered={false}>
          <PateoSearchForm
            searchItems={searchItems}
            fetchParams={{ type: 'template/postFetchPage', url: '/template/page' }}
            saveFormValues={val => this.setState({ formValues: Object.assign(formValues, val), selectedRowKeys: [] })}
            handleFormReset={() => this.setState({ formValues: {}, selectedRowKeys: [] })}
          />
        </Card>
        <Card bordered={false} style={{ marginTop: 12 }}>
          <div className="my_newItem">
            {filterAuth("template_doAdd", this.context.permissions, pathname) && <Button onClick={() => this.handleAdd()} size="small" icon={<PlusOutlined />} type="primary">新增</Button>}
          </div>
          <PateoTable
            extraHandle={true}
            formValues={formValues}
            tableProps={tableProps}
            fetchParams={{ type: 'template/postFetchPage', url: '/template/page' }}
          />
        </Card>
        <PateoModalForm
          style={{ top: 50 }}
          formItems={formItems}
          changeVisible={() => this.setState({ formData: {}, visible: false, postUrl: '' })}
          formData={formData}
          visible={visible}
          postUrl={postUrl}
          handleCallback={this.handleFlushPage}
          title={["新增模版", "编辑模版"]}
          messageInfo={["新增成功", "编辑成功"]}
          buttonName={["保存", "取消"]}
        />
      </div>
    );
  }
}

export default connect(mapStateToProps)(ImportTemplateList);
